package com.ycy.ss;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.ycy.ss.sync.Info;
import com.ycy.ss.sync.WriteInfo;


public class WriteJob implements Job{
	private Logger logger = LogManager.getLogger(WriteJob.class);

	public static List<Info> QUEUE_LIST = new CopyOnWriteArrayList<Info>();

	public void execute(JobExecutionContext context) throws JobExecutionException{
		logger.info("===== start write job =====");

		if (SSUtil.JOB_LOCK) {
			logger.warn("job is running...skip this time");
			return;
		} else {
			try {
				SSUtil.JOB_LOCK = true;
				// write
				if (QUEUE_LIST.size() != 0) {
					Info info = QUEUE_LIST.remove(0);
					for (String sync : Constant.getSync()) {
						try {
							String[] from_to = sync.split("-");
							String _from = from_to[0];
							String _to = from_to[1];

							// 比较sync.from=info.from,sync.to=to
							if (_from.equals(info.getFromSite())) {
								logger.info("===== write info [" + sync + "] =====");
								WriteInfo.write(info, _to);
							}
						} catch (Exception e) {
							logger.warn("", e);
						}
					}
				}

			} catch (Exception e) {
				logger.warn("", e);
			} finally {
				SSUtil.JOB_LOCK = false;
			}
		}

		logger.info("===== end write job =====");
	}

}
